# -*- coding: utf-8 -*-

import android
import sqlite3
import xmlrpclib
import ast 
import re 
import urllib
import time

droid = android.Android()

conn = sqlite3.connect('./openerp.db')

c = conn.cursor()
c.execute("create table if not exists config (user text,pass text,host text, port text,db text)")
conn.commit()

c.execute("select * from config")
row = c.fetchone()

username = 'admin' #the user
pwd = 'admin'      #the password of the user
dbname = 'sradvanced'    #the database
host = '10.10.10.250'
port = '8069'

if not row:
    c.execute("insert into config (user, pass, host, port, db) values (:user,:pass,:host,:port,:db)",{'user':'admin','pass':'admin','host':'10.10.10.250','port':'8069','db':'sradvanced'})
    conn.commit()
else:
    username = row[0]
    pwd = row[1]
    host = row[2]
    port = row[3]
    dbname = row[4]
    
c.close()

uid = False

def login(username, password, database, host, port):
    _db = droid.dialogGetInput('Database', '',database).result
    _host = droid.dialogGetInput('Host', '',host).result
    _port = droid.dialogGetInput('Port', '',port).result
    _user = droid.dialogGetInput('User Name', '',username).result
    _pass = droid.dialogGetPassword('Password').result
    try:
        sock_common = xmlrpclib.ServerProxy ('http://'+_host+':'+_port+'/xmlrpc/common')
        uid = sock_common.login(_db, _user, _pass)
        conn = sqlite3.connect('./openerp.db')
        c = conn.cursor()       
        c.execute("update config set user=:user, pass=:pass, host=:host, port=:port, db=:db",{'user':_user,'pass':_pass,'host':_host,'port':_port,'db':_db})
        conn.commit()
        c.close()
        #print uid
    except:
        return False
    return True 

def getTrackingLine(uid, pwd, dbname, host, port, classname, trackid, workcenter_id):
    #print classname, trackid, workcenter_id
    sock = xmlrpclib.ServerProxy('http://'+host+':'+port+'/xmlrpc/object')
    args = [('tracking_id', '=', int(trackid)),('workcenter_id','=',int(workcenter_id))] #query clause
    #print dbname, uid, pwd, args
    ids = sock.execute(dbname, uid, pwd, classname, 'search', args)
    #print ids
    fields = ['name','state'] #draft, done, cancel
    data = sock.execute(dbname, uid, pwd, classname, 'read', ids, fields)
    #print data
    if data:
        title = 'Confirm'
        message = (data[0]['name'] +u' เลือกรายการที่ต้องการ ?')
        droid.dialogCreateAlert(title, message)
        if data[0]['state'] == 'draft':
            droid.dialogSetPositiveButtonText(u'เสร็จ')
        elif data[0]['state'] == 'done':
            droid.dialogSetPositiveButtonText(u'ทำผิด')
        else:
            droid.dialogSetPositiveButtonText(u'รีเซ็ต')        
        droid.dialogSetNegativeButtonText(u'ลองใหม่')
        droid.dialogSetNeutralButtonText(u'กลับ')
        droid.dialogShow()
        response = droid.dialogGetResponse().result
        out = 0
        values = {}
        if response['which'] == 'positive':
            if data[0]['state'] == 'draft':
                #sock.exec_workflow (dbname, int(uid), pwd, classname, 'tracking_workorder_confirm', ids[0])
                values = {'state':'done','date_finished': time.strftime('%Y-%m-%d %H:%M:%S') }
            elif data[0]['state'] == 'done':
                values = {'state':'cancel','date_finished':False}
                #sock.exec_workflow (dbname, int(uid), pwd, classname, 'tracking_workorder_cancel', ids[0])
            else:
                #sock.exec_workflow (dbname, int(uid), pwd, classname, 'tracking_workorder_draft', ids[0])
                values = {'state':'draft','date_finished':False}
            sock.execute(dbname, uid, pwd, classname, 'write', ids, values)
            out = 1
        elif response['which'] == 'negative':
            out = 2
        else: 
            out = 3
    return out #response['which'] in ('positive', 'negative', 'neutral')

def getWorkcenter(uid, pwd, dbname, host, port):
    sock = xmlrpclib.ServerProxy('http://'+host+':'+port+'/xmlrpc/object')
    args = [('id', '!=', 0)] #query clause
    #print dbname, uid, pwd, args
    ids = sock.execute(dbname, uid, pwd, 'mrp.workcenter', 'search', args)
    #print ids
    fields = ['name'] #fields to read
    data = sock.execute(dbname, uid, pwd, 'mrp.workcenter', 'read', ids, fields)
    wclist = []
    for rec in data:
        wclist.append(str(rec['id'])+'::'+rec['name'])
    #print wclist
    title = "Work Centers"
    droid.dialogCreateAlert(title)
    droid.dialogSetSingleChoiceItems(wclist)
    droid.dialogSetPositiveButtonText("SELECT")
    droid.dialogShow()
    droid.dialogGetResponse().result
    menu_id = droid.dialogGetSelectedItems().result
    finish = False
    while not finish:
        code = droid.scanBarcode() 
        value = code[1]['extras']['SCAN_RESULT']
        datas = re.split(':',value)
        if datas[0] == 'tracking':
            wc_id = re.split('::', wclist[ menu_id[0] ])
            out = getTrackingLine(int(uid), pwd, dbname, host, port, 'ineco.mrp.production.tracking.line', datas[1], wc_id[0])
            if out == 3: 
                finish = True
    return True

def show_list_menu():
    title = 'MAIN MENU'
    options = ['SCAN', 'EXIT']
    droid.dialogCreateAlert(title)
    droid.dialogSetSingleChoiceItems(options)
    droid.dialogSetPositiveButtonText("SELECT")
    droid.dialogShow()
    droid.dialogGetResponse().result
    return droid.dialogGetSelectedItems().result

def make_fullscreen():
    layout = """
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/background"
            android:orientation="vertical" 
            android:layout_width="match_parent"
            android:layout_height="match_parent" 
            android:background="#ff000000">
    </LinearLayout>    
"""
    droid.fullShow(layout)
    return True 

def eventloop():
    #make_fullscreen()
    while True:
        #event=droid.eventWait().result
        selectmenu = show_list_menu()
        if selectmenu[0] == 1:
            break
        elif selectmenu[0] == 0:
            getWorkcenter(uid, pwd, dbname, host, port)
    return True

uid = login(username, pwd, dbname, host, port)
if uid:
    eventloop()